package com.cmos.um.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmos.um.beans.CtiMessage;
import com.cmos.um.beans.CtiMessageTask;
import com.cmos.um.iservice.ICtiMessageSV;
import com.cmos.um.iservice.ICtiMessageTaskSV;
import com.cmos.um.iservice.INgcsSV;
import com.cmos.um.utils.Result;
import com.cmos.um.utils.ResultUtil;
import com.cmos.um.utils.WSContent;
import com.cmos.um.utils.WSRtnJsonCtx;
import com.cmos.um.utils.http.RestClientHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@Service
public class NgcsSVImpl implements INgcsSV {

    private final static Logger logger = LoggerFactory.getLogger(NgcsSVImpl.class);


    @Autowired
    private ICtiMessageSV ICtiMessageSV;
    @Autowired
    private ICtiMessageTaskSV iCtiMessageTaskSV;
    @Autowired
    private RestClientHttpRequest clien;

    /**
     * 【操作】得到Cti和技能队列接口
     *
     * @param params 参数集MAP（含params参数——此参数在输入函数时为Json字符串）
     * @return Map<String,Object> 返回的数据（MAP形式）
     */
    @Override
    public Result getCtiAndSkill(JSONObject params) {

        //准备返回给ngcs的数据
        JSONObject toNgcs = new JSONObject();

        JSONObject P_params = params.getJSONObject("params");
        String taskId = P_params.getString("taskId");// 原始消息任务id
        String taskXfId = "000001" + WSContent.companyNo + "11" + taskId;// 统一管理数据库中的新方任务号
        String staffId = P_params.getString("staffId");
        JSONArray ctiAgentInfos = params.getJSONObject("object").getJSONArray("ctis");//坐席信息
        String RtnMsg = "成功";//返回的信息

        CtiMessage ctiInfo;//cti相关信息
        if (("00000000").equals(taskId)) {
            //根据taskid查询出所有cti的人工外呼任务号
            List<CtiMessageTask> list = iCtiMessageTaskSV.queryCtimessageConditional(taskId);
            if (list.size() == 0) {
                return ResultUtil.ngcsError("没有找到此人工外呼对应的cti");
            }
            int index = (int) (Math.random() * list.size());
            CtiMessageTask ctiMessageTask = list.get(index);//随机选出的cti
            ctiInfo = ICtiMessageSV.selectByPrimaryKey(ctiMessageTask.getCtiId());//根据ctiid查询出cti的相关信息
        } else {
            //根据原始的任务号查询cti信息
            ctiInfo = ICtiMessageSV.queryCtimessageBytaskId(taskId);
            if (ctiInfo == null) {
                return ResultUtil.ngcsError("没有找到此预测外呼对应的cti");
            }
            toNgcs.put("corecastOutCalSkill", taskXfId);// 预测外呼技能id
        }
        String ctiId = ctiInfo.getCtiId();
        String ctiIp = ctiInfo.getCtiIp();
        String ctiPort = ctiInfo.getCtiPort();

        String openeyeIp = ctiInfo.getSipIp();
        String openeyePort = ctiInfo.getSipPort();

        int agentCount = ctiInfo.getAgentCount();//坐席数
        //根据ctiid和taskid查询出对应的cti人工外呼号 00000000为默认人工
        CtiMessageTask ctitask = iCtiMessageTaskSV.queryCtiTaskConditional(ctiId, "00000000");
        if (ctitask == null) {
            return ResultUtil.error("-9999", "没有找到此人工外呼对应的cti");
        }
        String manuOutCallSkill = "000001" + WSContent.companyNo + "11" + ctitask.getTaskXfId();
        toNgcs.put("manuOutCallSkill", manuOutCallSkill);//人工外呼id
        //4 根据ctiId把ctiAgentInfos里的该坐席在该cti下的信息读出
        JSONObject suitCtiAgentInfo = null;
        for (Object ctiAgentInfo : ctiAgentInfos) {
            JSONObject json = (JSONObject) ctiAgentInfo;
            if (ctiId.equals(json.getString("ctiId"))) {
                suitCtiAgentInfo = json;
                break;
            }
        }
        if (suitCtiAgentInfo == null) {
            return ResultUtil.error("-9999", "没有匹配到对应的cti！");
        }
        //从传参中ctis中取到符合要求的返回
        String ccid = suitCtiAgentInfo.getString("ccId");
        String agentId = suitCtiAgentInfo.getString("agentId");

        JSONObject toCC = new JSONObject();
        toCC.put("agentId", agentId);
        WSRtnJsonCtx resultAgentInfo = clien.doPost(WSContent.agentUrl, ctiIp, "findAgent", WSContent._OTHER, toCC);
        JSONObject agentInfo = resultAgentInfo.getContextObj();
        if (!"0".equals(resultAgentInfo.getRescode()) || agentInfo == null) {
            logger.error("没有查询到此坐席的信息，返回的信息为：" + resultAgentInfo.getOutputObj());
            return ResultUtil.error("-9999", "没有查询到此坐席的信息！");
        }
        agentInfo.put("taskId",taskXfId);
        WSRtnJsonCtx resultUpdateAgent = clien.doPost(WSContent.agentUrl, ctiIp, "operateAgent", WSContent._UPDATE, agentInfo);
        if (!"0".equals(resultUpdateAgent.getRescode())) {
            logger.error("修改坐席信息失败！,返回的信息为：" + resultUpdateAgent.getResJsonObj());
            return ResultUtil.error("-9999", "修改坐席信息失败！");
        }

        toCC.put("serviceId", taskXfId);
        toCC.put("serviceType", "3");
        WSRtnJsonCtx wsRtnJsonCtx = clien.doPost(WSContent.servUrl, ctiIp, "operateMember", "0", toCC);
        //如果返回的接口是2004
        if ("2004".equals(wsRtnJsonCtx.getRescode())) {
            RtnMsg = "坐席已绑定";
        }
        if (!"0".equals(wsRtnJsonCtx.getRescode()) && !"2004".equals(wsRtnJsonCtx.getRescode())) {
            logger.error("调用cti绑定坐席接口失败，返回的信息为：" + wsRtnJsonCtx.getResJsonObj());
        }
        CtiMessage ctimessage = new CtiMessage();
        ctimessage.setCtiId(ctiId);
        ctimessage.setAgentCount(agentCount + 1);
        //根据ctiid修改task_count数
        ICtiMessageSV.updateByPrimaryKeySelective(ctimessage);
        toNgcs.put("staffId", staffId);
        toNgcs.put("ctiId", ctiId);
        toNgcs.put("ccId", ccid);
        toNgcs.put("agentId", agentId);
        toNgcs.put("ctiIp",  ctiIp);
        toNgcs.put("ctiPort",  ctiPort);
        toNgcs.put("ctiWebIp",  ctiInfo.getCtiSignInIp());
        toNgcs.put("ctiWebPort",  ctiInfo.getCtiSignInPort());
        toNgcs.put("openeyeIp", openeyeIp);
        toNgcs.put("openeyePort", Integer.parseInt(openeyePort));
        return ResultUtil.ngcsSuccess(RtnMsg, toNgcs);
    }
}
